package com.ruitu.mall_98_1.rong;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.utils.UIUtils;
import com.google.gson.Gson;
import com.ruitu.mall_98_1.R;
import com.ruitu.mall_98_1.dao.P_Global;
import com.ruitu.mall_98_1.dao.api.APIRetrofit;
import com.ruitu.mall_98_1.product.activity.ProductDetailActivity;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.product.Product;
import com.ruitu.router_module.bean.product.RongMsgContent;

import io.rong.imkit.RongIM;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.RichContentMessage;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ConversationActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView tv_title;

    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conversation);
        toolbar = findViewById(com.beanu.arad.R.id.toolbar);
        tv_title = findViewById(R.id.tv_title);

        toolbar.setNavigationIcon(com.beanu.arad.R.mipmap.arad_ic_back_normal);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        toolbar.setTitle("");

        String titile = "客服";
        try {
            titile = getIntent().getData().getQueryParameter("title");
        } catch (Exception e) {
        }
        tv_title.setText(titile);

        RongIM.getInstance().setSendMessageListener(new RongIM.OnSendMessageListener() {
            @Override
            public Message onSend(Message msg) {
                return msg;
            }

            @Override
            public boolean onSent(Message msg, RongIM.SentMessageErrorCode sentMessageErrorCode) {
                byte[] msgByte = msg.getContent().encode();
                String msgContent = new String(msgByte);
                RongMsgContent realContent = gson.fromJson(msgContent, RongMsgContent.class);
//                Logg.i("msgContent = " + msgContent);
//                Logg.i("onSent执行了....." + "发送人:" + msg.getSenderUserId() + ",接收者:" + msg.getTargetId() + ",内容:" + realContent.getContent());

                if (null == sentMessageErrorCode) {
                    return true;
                }
                return false;
            }
        });

        final Product p = P_Global.P;
        final String targetId = P_Global.T_ID;
        if (null != p && !TextUtils.isEmpty(targetId)) {
            sendWelcomeMsg(targetId);//请求欢迎消息
            UIUtils.showAlertDialog(getSupportFragmentManager(), "温馨提示", "是否发送当前商品信息给商家？", "发送",
                    "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            sendPicTxtMsg(p, targetId);
                        }
                    }, null);
        }
        setListeners();//设置会话界面监听
    }

    private void setListeners() {
        RongIM.getInstance().setConversationClickListener(new RongIM.ConversationClickListener() {
            @Override//点击用户头像
            public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo, String s) {
                return false;
            }

            @Override//长按用户头像
            public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo, String s) {
                return false;
            }

            @Override//点击消息
            public boolean onMessageClick(Context context, View view, Message message) {
                MessageContent msgContent = message.getContent();
                if (msgContent instanceof RichContentMessage) {
                    //点击的是图文消息,此项目可以认为是发送的商品
                    String extra = ((RichContentMessage) msgContent).getExtra();
                    if (TextUtils.isEmpty(extra)) {
                        ToastUtils.showShort("商品信息有误!");
                    } else {
                        Product product = new Product();
                        product.setGoodId(extra);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("product", product);
                        Intent intent = new Intent(ConversationActivity.this, ProductDetailActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                    return true;
                }
                return false;
            }

            @Override//点击链接消息
            public boolean onMessageLinkClick(Context context, String s, Message message) {
                return false;
            }

            @Override//长按消息
            public boolean onMessageLongClick(Context context, View view, Message message) {
                return false;
            }
        });
    }

    private void sendPicTxtMsg(Product p, String targetId) {
        RichContentMessage richMsg = RichContentMessage.obtain(p.getGoodName()
                , "价格￥" + p.getGoodMarket(), Config.BASE_URL + p.getImageUrl());
        richMsg.setExtra(p.getGoodId());//设置消息存储的信息,这里存商品id
        Message myMsg = Message.obtain(targetId, Conversation.ConversationType.PRIVATE, richMsg);
        RongIM.getInstance().sendMessage(myMsg, null, null, new IRongCallback.ISendMessageCallback() {
            @Override
            public void onAttached(Message message) {
                //消息本地数据库存储成功的回调
            }

            @Override
            public void onSuccess(Message message) {
//                ToastUtils.showShort("消息发送成功" + ((RichContentMessage) message.getContent()).getTitle());

            }

            @Override
            public void onError(Message message, RongIMClient.ErrorCode errorCode) {
//                ToastUtils.showShort("消息发送失败");
            }
        });
    }

    private void sendWelcomeMsg(String targetId) {//提醒卖家发送欢迎消息
//        if (P_Global.LAST_TIME > 0 && null != P_Global.T_ID_OLD) {
//            if (TextUtils.equals(P_Global.T_ID_OLD, targetId) && System.currentTimeMillis() - P_Global.LAST_TIME < 60000) {
//                //同一件商品,一分钟以内咨询多次
//                return;
//            }
//        } else {
//            P_Global.LAST_TIME = System.currentTimeMillis();
//            P_Global.T_ID_OLD = targetId;
//        }
        APIRetrofit.getDefault().reqMsgWelcome(targetId, AppHolder.instance().getUser().getAccountId())
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult>() {
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseResult baseResult) {
                        Logg.i(baseResult.getMsg());
                        if (baseResult.isSuccess()) {

                        } else {

                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        P_Global.P = null;
    }
}
